<template>
  <div>
    <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-collapse v-model="activeNames" accordion  v-loading="loading" :element-loading-text="loadingText">
        <el-collapse-item title="Price Setting List" name="1"  style="padding-left: 15px;">
          <el-tag style="margin: 5px 5px;min-width:215px;"
                  v-for="(tag, index) in dataList"
                  closable
                  :type="(index+1 % 1 == 0) ? 'success' : (index % 2 == 0) ? 'info' : (index % 3 == 0) ? 'warning' : (index % 4 == 0) ? 'danger' : ''"
                  @click="clickTag(index)" @close="closeTag(tag.id)">
              {{tag.currency}}:{{tag.price}}[{{tag.date}},{{tag.platform}}]
          </el-tag>

        </el-collapse-item>
        <el-collapse-item title="Add Price Setting" name="2" style="padding-left: 15px;">
          <el-form ref="formData" :model="formData"  :rules="rules" label-width="125px">
            <el-form-item label="Physical Room Id" class="form-item-wd" >
              <el-input
                placeholder="Physical Room Id"
                v-model="pid"
                :disabled="true">
              </el-input>
            </el-form-item>

            <!--
            <el-form-item label="Logical Room Id"  prop="logical_room_id" class="form-item-wd">
              <el-select v-model="formData.logical_room_id" placeholder="Please Select A Logical Room Id"  class="input-size">
                <el-option
                  v-for="item in logicRoomList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            -->

            <el-form-item label="Date Range"  prop="dateRange">
              <div class="block" style="width: 100%">
                <el-date-picker style="width: 70%"  class="input-size"
                                v-model="formData.dateRange"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="to"
                                start-placeholder="Start Date"
                                end-placeholder="End Date"
                                :picker-options="pickerOptions"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                :disabled="dateRangeDisabled">
                </el-date-picker>
              </div>
            </el-form-item>


            <el-form-item label="Platform"  prop="platform" class="form-item-wd">
              <el-select v-model="formData.platform" placeholder="Please Select A Platform"  class="input-size">
                <el-option :value="item.value" v-for="item in platforms">{{item.label}}</el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="Currency"  prop="currency" class="form-item-wd">
              <el-select v-model="formData.currency" placeholder="Please Select A Currency" class="input-size">
                <el-option :value="currency"  v-for="(currency, index) in currencies">{{currency}}</el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="Price"  prop="price" class="form-item-wd">
              <el-input v-model="formData.price" placeholder="Please Enter Price"/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doSave">Save Changes</el-button>
              <el-button  @click="doClose">Close</el-button>
              <el-button  @click="doReset">Add Data</el-button>
              <el-button type="danger" icon="el-icon-refresh" circle @click="doSynchro"></el-button>
            </el-form-item>
          </el-form>

        </el-collapse-item>
      </el-collapse>

    </el-scrollbar>


  </div>

</template>

<script>
  import config from '@/config';
  import {addModel,searchModel,get,updateModel,deleteModel,addModels,updateModels} from "@/api/model";
  import {submitAction} from "@/api/task";

  export default {
    name: "PriceSettingForm",
    props:["pid","roomId","listingId"],
    data() {
      return {
        model: 'PriceCalendar', //
        bodyHeight:900,
        parentObj : null, //父对象
        loading:false,
        loadingText:'data load ...',
        totalDays:0,
        id:null,    //当前选中的房态ID
        activeNames: ['1','2'],
        dataList : [],
        logicRoomList:[],
        currencies: null,
        platforms:null,
        dateRangeDisabled:false,//
        formData: this.getInitFormData(),
        rules: this.getInitRules(),
        pickerOptions: {
          shortcuts: [{
            text: 'Last week',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: 'Last month',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: 'Last three months',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }],
        }
      }
    },
    created() {
      const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
      // console.log("bodyHeight="+_bodyHeight);
      this.bodyHeight = _bodyHeight - 65;
      this.currencies = config.CURRENCY
      this.platforms = config.PLATFORM
    },
    mounted(){

    },
    methods: {
      getInitFormData(respData){
        let _id = null;
        let _physical_room = this.roomId;
        let _platform = null;
        let _price = 0;
        let _currency = "JPY";
        let _date = null;
        let _dateRange = [];
        if(respData){
          _id = respData.id;
          _physical_room = respData.physical_room;
          _platform = respData.platform;
          _price = respData.price;
          _currency = respData.currency;
          _date = respData.date;
          _dateRange = respData.dateRange;
        }
        return  {
          id: _id,
          physical_room: _physical_room,
          platform:_platform,
          price:_price,
          currency:_currency,
          date: _date,
          dateRange:_dateRange
        };
      },
      getInitRules() {
        const _this = this;
        const custRulesCfg = this.getCustRulesConfig();
        const priceValid = custRulesCfg.floatValid('Price',1,100000);
        return {
          /*
          logical_room_id:[
            { required: true, message: 'Please Enter Logical_Room_Id', trigger: 'blur' },
            { min: 1, max: 100, message: '1 to 100 characters in length', trigger: 'blur' }
          ],*/
          dateRange:[
            { required: true, message: 'Please Select A Date range', trigger: 'change', type: 'array'}
          ],
          platform:[
            { required: true, message: 'Please Select A Platform', trigger: 'change'}
          ],
          currency:[
            { required: true, message: 'Please Select A Currency', trigger: 'change'}
          ],
          price:[
            { required: true,validator: priceValid,trigger: 'blur' }
          ]
        };
      },
      getCustRulesConfig(){
        return {
          intValid: function(label, min, max){
            const intValidFun = (rule, value, callback) => {
              if (!value) {
                callback(new Error('Please Enter '+label));
              }
              try{
                value = parseInt(value);
              }catch (e) {
                callback(new Error(label+' Must be an integer value'));
              }

              if (!Number.isInteger(value)) {
                callback(new Error(label+' Must be an integer value'));
              }
              if(min != null && max != null){
                if(value < min || value > max){
                  callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                }else{
                  callback();
                }
              }
              if(min != null && max == null){
                if (min && min > value) {
                  callback(new Error(label+' Must be greater than or equal to '+min));
                } else {
                  callback();
                }
              }

              if(max != null && min == null){
                if (max && value > max) {
                  callback(new Error(label+' Must be less than or equal to '+max));
                } else {
                  callback();
                }
              }
            };
            return intValidFun;
          },
          floatValid: function(label, min, max,custCb){
            const intValidFun = (rule, value, callback) => {
              if (!value) {
                callback(new Error('Please Enter '+label));
              }
              try{
                value = parseFloat(value);
              }catch (e) {
                callback(new Error(label+' Must be an float value'));
              }

              if (!Number.isInteger(value)) {
                callback(new Error(label+' Must be an float value'));
              }
              if(min != null && max != null){
                if(value < min || value > max){
                  callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                }else{
                  if(custCb){
                    custCb(rule, value, callback);
                  }else{
                    callback();
                  }
                }
              }
              if(min != null && max == null){
                if (min && min > value) {
                  callback(new Error(label+' Must be greater than or equal to '+min));
                } else {
                  callback();
                }
              }

              if(max != null && min == null){
                if (max && value > max) {
                  callback(new Error(label+' Must be less than or equal to '+max));
                } else {
                  callback();
                }
              }

            };
            return intValidFun;
          },
        };
      },
      refresh(_parentObj){
        console.log("refresh to do ...");
        this.parentObj = _parentObj;
        this.loadDatas();
      },
      setLogicRoomList(_logicRoomList){
        this.logicRoomList = _logicRoomList;
      },
      /**
       * 加载数据
       */
      loadDatas(){
        console.log("loadDatas to do ...");
        this.dataList = this.parentObj.selPriceListDatas;
        this.doReset();
      },
      /**
       * 保存数据
       */
      doSave(){
        console.log("doSave to do ...");
        const _this = this;
        this.formData.physical_room = this.roomId;
        let _formData = this.formData;
        for(var key in _formData){
          const val = _formData[key];
          if(!val && (val !== 0 || val !== '0')){
            delete _formData[key];
          }
        }

        this.$refs['formData'].validate((valid) => {
          if (valid) {
            _this.loading = true;
            if(_this.id){
              this.updateData(_formData);
            }else{
              const _dateRange = _formData.dateRange;
              const _firstDate = _dateRange[0];
              const _lastDate = _dateRange[1];
              const firstDate =  moment(_firstDate).format('YYYY-MM-DD');
              let lastDate = moment(_lastDate).add(1, 'd');
              lastDate = moment(lastDate).format('YYYY-MM-DD');
              console.log("lastDate="+lastDate);
              const _roomId = this.roomId;
              const _pars = {physical_room:_roomId};
              searchModel('PriceCalendar', {
                order_by: "-id",
                page_size: 1000,
                raw_filter: {
                  date__gte: firstDate,
                  date__lt: lastDate
                },
                search_keys: _pars
              }).then(res => {
                _this.loading = false;
                const list = res.data.list;
                this.saveData(list);
              }).catch(err => {
                _this.loading = false;
                console.error(err);
              });
            }
          } else {
            console.log('error submit!!');
            _this.$message.error('Please Check Input Form Data Has Errors!');
            return false;
          }
        });
      },
      updateData(formData){
        delete formData["dateRange"];
        const _this = this;
        this.loading = true;
        updateModel(this.model, _this.id, formData).then(res => {
          _this.loading = false;
          _this.$message({
            type: 'info',
            message: 'Save Data Success!'
          });
          _this.doSynchro();
          this.reloadParentData();
        }).catch(reason => {
          _this.loading = false;
          console.error(reason);
        });
      },
      saveData(list){
        const _this = this;
        const _formData = this.formData;
        const _dateRange = _formData["dateRange"];
        const _firstDate = _dateRange[0];
        const _lastDate = _dateRange[1];
        const days = this.getDays(_firstDate,_lastDate);
        const dateArr = [
          moment(_firstDate).format('YYYY-MM-DD')
        ];
        for(let i=1; i<=days; i++){
          let date = moment(_firstDate).add(i, 'd');
          date = moment(date).format('YYYY-MM-DD')
          dateArr.push(date);
        }
        this.loading = true;
        const promiseData = {batchInsertPromise:null, batchUpdatePromise:null};
        if(null == list || list.length == 0){ //批量插入
          this.batchInsert(dateArr, true);
        }else{ //更新或插入
          const _platform = _formData.platform;
          const samePlatformList = list.filter(item => {
            return item.platform == _platform;
          });
          console.log("====samePlatformList===");
          console.log(samePlatformList);
          if(null == samePlatformList || samePlatformList.length == 0){ //批量插入
              promiseData.batchInsertPromise = this.batchInsert(dateArr);
          }
          const _dataArr = this.groupData(dateArr, samePlatformList);
          const insertDateArr = _dataArr[0];
          const updateDatas = _dataArr[1];
          console.log("===== insertDateArr And updateDatas =====");
          console.log(insertDateArr);
          console.log(updateDatas);
          console.log("===== insertDateArr And updateDatas End =====");
          let methodArr = [];
          let isRefresh = false;
          if(insertDateArr){
            isRefresh = (!updateDatas || updateDatas.length == 0);
            promiseData.batchInsertPromise = this.batchInsert(insertDateArr,isRefresh);
          }
          if(updateDatas){
            isRefresh = (!insertDateArr || insertDateArr.length == 0);
            promiseData.batchUpdatePromise =  this.batchUpdate(updateDatas,isRefresh);
          }

          if(promiseData.batchInsertPromise)  methodArr.push(promiseData.batchInsertPromise);
          if(promiseData.batchUpdatePromise)  methodArr.push(promiseData.batchUpdatePromise);

          if(!methodArr || methodArr.length == 0) return;

          Promise.all(methodArr).then((res) => {
              console.log(" Promise.all.success ... ");
              this.doSynchro();
              this.reloadParentData();
          }).catch(err => {
            console.error("======== 保存改价记录失败 =======");
             console.error(err);
          });
        }
      },
      groupData(dateArr, samePlatformList){
        let updateData = [];
        let insertDateArr = [];
        dateArr.forEach(date => {
          let flag = false;
          for(let i=0,count=samePlatformList.length; i<count; i++){
            const data = samePlatformList[i];
            const _date = data.date;
            if(date == _date){
              updateData.push(data);
              flag = true;
              break;
            }
          }
          if(!flag){ //要插入的日期
            insertDateArr.push(date);
          }
        });
        return [insertDateArr, updateData];
      },
      /**
       * 批量更新
       */
      batchUpdate(datas){
        console.log("batchUpdate un do ...");
        const _this = this;
        const { platform, price, currency } = this.formData;

        const dataArr = datas.map(data => {
          data.platform = platform;
          data.price = price;
          data.currency = currency;
          return data;
        });
        return new Promise((resolve, reject) => {
          updateModels(_this.model, dataArr).then(res => {
            resolve(res);
            console.log("batchUpdate.success ...");
            console.log(res);
          }).catch(err =>{
            console.log("batchUpdate.failure ...");
            console.error(err);
            reject(err);
          });
        });
      },
      /**
       * 批量插入
       */
      batchInsert(dateArr, isRefresh){
        const _this = this;
        console.log("batchInsert un do ...");
        const { physical_room ,platform, price, currency } = this.formData;

        const dataArr = dateArr.map(item => {
          return {physical_room:physical_room, platform:platform, price:price, currency:currency, date:item};
        });
       // console.log(dataArr);
        return new Promise((resolve, reject) => {
            addModels(_this.model, dataArr).then(res => {
              this.loading = false;
              resolve(res);
              this.reloadParentData();
              console.log("batchInsert.success ...");
              console.log(res);
            }).catch(err =>{
              this.loading = false;
               console.log("batchInsert.failure ...");
               console.error(err);
               reject(err);
            });
        });
      },
      /**
       *  获取截止日期和起始日期之间的天数
       * */
      getDays(startDate, endDate){
        const days = moment(endDate).diff(moment(startDate), 'days')
        //console.log(endDate+" - "+startDate+ "="+ days);
        return days;
      },
      reloadParentData(){
        const _this = this;
        this.doClose();
        _this.parentObj.loadOrderData((list) =>{
          const _myPriceList = list.filter(item => {
            return item.physical_room == _this.roomId;
          });
          if(!_myPriceList || _myPriceList.length==0){
            this.dataList = [];
            return;
          }
          this.dataList = _myPriceList;
        });
      },
      clickTag(index){
        const _this = this;
        const _data = this.dataList[index];
        this.id = _data.id;
        console.log(_data);
        const date = _data.date;
        const _date = new Date(date.replace(/-/g, "\/"));
        const _dateRange = [_date,_date];
        _data.dateRange = _dateRange;
        this.dateRangeDisabled = true; //禁用日期选择。修改时不能修改日期，因为会造成跟其它日期冲突。
        this.formData = this.getInitFormData(_data);
      },
      closeTag(_id){
        const _this = this;
        this.id = _id;
        this.loading = true;
        deleteModel(this.model, _this.id).then(res => {
          this.loading = false;
          _this.$message({
            type: 'info',
            message: 'Save Data Success!'
          });
          _this.reloadParentData();
        }).catch(reason => {
          _this.loading = false;
          console.log("deleteModel Failure...");
          console.error(reason);
          //_this.$message.error('Please Check Input Form Data Has Errors!');
        });
      },
      getParent(){
        return this.parentObj ||  this.$parent;
      },
      doClose(){
        const _parent = this.parentObj ||  this.$parent;
        console.log(_parent);
        _parent.closeDrawer();
      },
      /**
       * 重置表单
       */
      doReset(){
        this.formData = this.getInitFormData();
       // this.logicRoomList = [];
        this.id = null;
        this.loadingText = "data loading ...";
        this.loading = false;
        this.dateRangeDisabled = false;
        if(this.$refs['formData']) this.$refs['formData'].resetFields();
      },
        /**
         * ActionTask ABNB API 同步
         */
        doSynchro(){
            const _this = this;
            if(!this.listingId){
                _this.$message.error('PhysicalRoomListing id is null,Please Check Data...!');
                return;
            }
            this.loadingText = "Calling API: sync_price_to_airbnb ...";
            this.loading = true;

            submitAction("PhysicalRoomListing", this.listingId,"sync_price_to_airbnb").then(res => {
                this.loading = false;
                _this.$notify({
                    title: 'Success',
                    message: 'ListingId:'+ this.listingId+' call API:sync_price_to_airbnb succeeded !',
                    type: 'success'
                });


            }).catch(reason => {
                _this.loading = false;
                console.log("deleteModel Failure...");
                console.error(reason);
                _this.$notify.error({
                    title: 'Error',
                    message: 'API:sync_price_to_airbnb  call error !'
                });
                //_this.$message.error('Please Check Input Form Data Has Errors!');
            });
        }
    }
  }
</script>

<style scoped>
  .input-size{
    width: 95%;
  }
  .form-item-wd{
    margin-right: 20px;
  }
</style>

